package com.simple.chinagpay.service.impl;

import com.simple.chinagpay.service.CallbackService;
import com.simple.common.entity.constant.Payment;
import com.simple.common.entity.dto.pay.CallbackDynamicDto;
import com.simple.common.entity.dto.pay.CallbackRspDto;
import com.simple.common.entity.po.sys.Trade;
import com.simple.common.framework.context.Contexts;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author yasud
 * @date 2021年03月10日 16:01
 * @description
 */
@Service
public class CallbackServiceImpl implements CallbackService {

    @Override
    @SneakyThrows
    public CallbackRspDto callback(CallbackDynamicDto dto) {
        Trade trade = dto.getTrade();
        Map<String, Object> map = Contexts.OBJECTMAPPER.readValue(dto.getBody(), Map.class);
        String resultCode = map.get("resultCode") + "";
        String transNo = map.get("transNo") + "";
        if (StringUtils.isNotBlank(transNo)) {
            trade.setChannelOrderNo(transNo);
        }
        if ("00".equals(resultCode)) {
            trade.setStatus(Trade.Status.SUCCESS);
            trade.setMsg(Payment.TRADE_STATUS_DESCRIBE.EVEN_SERIAL_STATUS_PAYMENT_SUCCESS_MSG);
            trade.setChannelStatus(resultCode);
            trade.setChannelMsg(map.getOrDefault("resultMessage", "").toString());
        }
        else {
            trade.setStatus(Trade.Status.FAILED);
            trade.setMsg(map.getOrDefault("resultMessage", "").toString());
            trade.setChannelStatus(resultCode);
            trade.setChannelMsg(map.getOrDefault("resultMessage", "").toString());
        }

        CallbackRspDto rspDto = new CallbackRspDto();
        rspDto.setTrade(trade);
        return rspDto;
    }
}
